import qs from 'qs'
import axios from 'axios'
import store from '@/store'
class CancelRequest {
  static pendingRequest = new Map()

  // 根据请求信息生成唯一标识key
  static geterateReqKey(config) {
    const { url, method, params, data } = config
    const getData = typeof params !== 'string' ? qs.stringify(params) : params
    const postData = typeof data !== 'string' ? qs.stringify(data) : data
    return [url, method, getData, postData].join('&')
  }

  // 把当前请求信息添加到pendingRequest对象中
  static addPendingRequest(config, CancelToken) {
    const requestKey = this.geterateReqKey(config)
    config.cancelToken =
            config.cancelToken ||
            new axios.CancelToken(cancel => {
              if (!this.pendingRequest.has(requestKey)) {
                // 把请求取消方法作为 map 值存起来
                this.pendingRequest.set(requestKey, cancel)
              }
            })
  }

  // 检查是否存在重复请求，若存在则取消前一次请求
  static removePendingRequest(config) {
    const requestKey = this.geterateReqKey(config)
    if (this.pendingRequest.has(requestKey)) {
      const cancel = this.pendingRequest.get(requestKey)
      // 取消请求
      cancel(requestKey)
      // 删除map中对应的属性
      this.removeRequestKey(config)
    }
  }

  // 从pendingRequest中删除对应的key
  static removeRequestKey(config) {
    const requestKey = this.geterateReqKey(config)
    if (this.pendingRequest.has(requestKey)) {
      this.pendingRequest.delete(requestKey)
    }
  }

  /**
   * 路由跳转时清空正在进行所有的请求
   */
  static clearAllPending() {
    for (const [requestKey, cancel] of this.pendingRequest) {
      cancel(requestKey)
    }
    this.pendingRequest.clear()
  }
}
export default CancelRequest
